package top.lixunda.books3.util;

import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import top.lixunda.books3.model.SmsResult;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

@Component
public class SmsUtil {

    private static final String operation = "/industrySMS/sendSMS";

    public static final String REGISTER = "201942344";

    public static final String FIND_PASSWORD = "201967348";
    
    public SmsResult sendSms(String code, String to, final String aimStr) {
    	String url = Config.BASE_URL + operation;
        String body = "accountSid=" + Config.ACCOUNT_SID + "&to=" + to + "&templateid=" + aimStr + "&param=" + code + "," + "5"
                + createCommonParam();
        //提交请求
        String result = HttpUtil.post(url, body);
        if(result == null){
        	return null;
        }
        Log.d("sms", "code = " + code + ", to = " + to + ", result = " + result);
        Gson gson = new Gson();
        return gson.fromJson(result, SmsResult.class);
    }
    

	/**
     * 构造通用的参数timestamp. sig和respDataType;
     * @return 返回构造好的参数字符串
     */
    public String createCommonParam(){
        //时间戳
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
        String timestamp = format.format(new Date());
        //签名
        String sig = DigestUtils.md5Hex(Config.ACCOUNT_SID + Config.AUTH_TOKEN + timestamp);

        return "&timestamp=" + timestamp + "&sig=" + sig + "&respDataType=" + Config.RESP_DATA_TYPE;
    }
	
	private class Config{
	    /**
	     * URL
	     */
	    protected static final String BASE_URL = "https://api.miaodiyun.com/20150822";

	    /**
	     * 账号
	     */
	    protected static final String ACCOUNT_SID = "c9fd08c43c90496eb58e0b7a4c7c19ca";

	    /**
	     * KEY
	     */
	    protected static final String AUTH_TOKEN = "63cd14ab36244c3fa4002178368adf1b";

	    /**
	     * 相应数据类型, JSON或者XML
	     */
	    protected static final String RESP_DATA_TYPE = "json";
	}
}
